'''
数据库相关的操作
'''

import pymysql
from mysql.connector import cursor


def connect(db_info: dict):
    '''
    连接数据库
    :param db_info:    字典格式的，数据库相关的信息
            {"host":"192.168.0.103","port":3306,"user":"root","pwd":"123456","dbname":"apple"}
    :return:    连接对象
    '''

    try:
        conn = pymysql.connect(user=db_info['user'],
                               password=db_info['pwd'],
                               host=db_info['host'],
                               database=db_info['dbname'],
                               port=db_info['port'],
                               charset="utf8", )
        print("连接数据库成功")
        return conn
    except Exception as e:
        print(f"连接数据库异常，异常信息为：{e}")


def disconnect(conn):
    '''
    断开连接
    :param conn: 连接对象
    :return:
    '''
    try:
        conn.close()
    except Exception as e:
        print(f"断开数据库连接异常，异常为：{e}")


def execute(conn, sql):
    try:
        c = conn.cursor()  # 获取游标，类似createstatement
        c.execute(sql)  # 使用游标执行sql语句
        conn.commit()  # 提交
        print(f"执行{sql}成功")
    except Exception as e:
        print(f"执行{sql}异常，异常为：{e}")


def delete_user(db_info,phone):
    '''
    根据手机号删除用户
    :param phone:
    :return:
    '''

    conn = connect(db_info)
    execute(conn, f"delete from member where mobilephone={phone}")
    disconnect(conn)


if __name__ == '__main__':
    db_info = {"host": "192.168.0.103", "port": 3306, "user": "root", "pwd": "123456", "dbname": "apple"}
    connect(db_info)
    conn = connect(db_info)
    execute(conn, "delete from member where mobilephone=13333333333")
    # disconnect(conn)
    # delete_user(db_info,"13333333333")
